<?php
namespace Home\Controller;
use Think\Controller;
class RandomController extends Controller {
    public function index(){
		
		/*=========定义变量=======*/
		$openid   = I('post.openid');
		$QUESTION = M('questionbank');
		$ANSWER   = D('answer');  //需定义answer模型以进行正确的读写操作
		$openid =1;
		/*======获取答题数量======*/		
		!strlen($openid) || $itemnum  =   $ANSWER->where("openid={$openid}")->count();
		
		/*======读取随机试题======*/
		$count = $QUESTION->count();
		$min   = $QUESTION->min('id');				
		$item  = $QUESTION->where("id=".rand($min,$min+$count))->find();	
		
		/*======设定模版变量======*/
		$this->assign('item',$item);
		$this->assign('itemnum',$itemnum);
		$this->assign('openid',$openid);
		$this->display();
    }
	public function recordOption($answer,$openid=0,$itemid,$rightans){
		//I("post.record");
		

		$ANSWER = D('answer');
		if($ANSWER->create()){
			
			$answer = substr($answer,strlen($answer)-1,strlen($answer));
			
			$record['openid'] = $openid;
			$record['time']   = date("Y-m-d H:i:s");
			$record['itemid'] = $itemid;
			$record['answer'] = $answer;
			$record['right_lab'] = ($answer==$rightans)? 1:0;
			
			$ANSWER->add($record);			
		}else{
			$this->error($ANSWER->getError());			
		}
	}
	
	public function getRightAns(){
		/*=========判断是否通过ajax方式传输数据=======*/
		if(IS_AJAX){
			/*=========定义变量=======*/
            $itemid   = I('post.itemid');
            $openid   = I('post.openid');
            $answer   = I('post.answer');
			$QUESTION = M('questionbank');
			
			/*=======获取正确答案=====*/	
			$ajaxreturn['rightans']     = $QUESTION->where("id={$itemid}")->getField("rightans");
			$ajaxreturn['que_analysis'] = $QUESTION->where("id={$itemid}")->getField("que_analysis");
			
			/*=======记录答题情况=====*/
			$this->recordOption($answer,$openid,$itemid,$ajaxreturn['rightans']);
		
			/*====返回答案解析到前台==*/
			$this->ajaxReturn($ajaxreturn);     
        }
		else $this->ajaxReturn('非法的请求方式'); 
		
	}   
}




?>